//
//  SAHomeVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/1/25.
//

#import "SAHomeVC.h"
#import "SAIndexCell.h"
#import "SAIndexFlowLayout.h"
#import "SAHomeMenuListAPI.h"
#import "SAhomeMenuModel.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SASummaryQueryAPI.h"
#import "SAShopPreviewVC.h"
#import "SAMarketingVC.h"
#import "SATutorialVC.h"
#import "SALoginVC.h"
#import "SAShopSaleVC.h"
#import "SAWarehousingVC.h"
#import "SAStoreManagementVC.h"
#import "SAMyAccountVC.h"
#import "SACloudPrintHeartbeatAPI.h"
#import "SAAddInventoryVC.h"
#import "SAVipManagementVC.h"
#import "SAUserExpireAPI.h"
#import "SAUserExpireModel.h"
#import "SAUserExpireView.h"
#import "SASupplierVC.h"
#import "SAStaffManagementVC.h"
#import "SAPrintLableVC.h"
#import "SAReturnGoodsVC.h"
#import "SAOperatingProfitVC.h"
#import "SACollectionPayVC.h"
#import "SAOpenPayVC.h"
#import "SACommonProblemsVC.h"
#import "SACommonProblemsCell.h"
#import "SACommonProblemsModel.h"
#import "SASystemFaqTypeListAPI.h"
#import "SACommonProblemsDetailVC.h"
#import <WechatOpenSDK/WXApi.h>
#import "SAShopAllocateVC.h"
#import "SAShopReturnGoodsVC.h"
#import "ConnecterManager.h"
#import "SAShopWKWebVC.h"
#import "SABatchPurchaseVC.h"
#import "SAShopWKWebVC2.h"
#import "SAMemberTopUpRecordVC.h"
#import "SAActivityListAPI.h"
#import "SAActivityListModel.h"
#import "SAMemberMessageVC.h"
#import "SATrialVersionView.h"
#import "SAExpirationPaymentView.h"
#import "SATrialVersionVC.h"
#import "SAExpirationPaymentVC.h"
#import "SAPaymentWKWebVC.h"
#import "HDTabBarController.h"
#import "SARenewTypeAPI.h"
#import "SAServiceMarketListAPI.h"
#import "SAServiceMarketModel.h"
#import "SAServiceMarketView.h"
#import "SAOpenVipWKWebVC.h"
#import "SACategoryView.h"

#define KMenuId @"-29834" //自定义，防止和后端重复

@interface SAHomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HTTPAPIDelegate,UITableViewDelegate,UITableViewDataSource,JXCategoryListContainerViewDelegate>

@property (nonatomic, strong) UIImageView *topImageV;
@property (nonatomic, strong) UIImageView *topImageV2;
@property (nonatomic, strong) UIImageView *whiteImageV;
@property (nonatomic, strong) UIImageView *headerImageV;
@property (nonatomic, strong) UILabel *userNameLab;
@property (nonatomic, strong) UIImageView *vipImageV;
@property (nonatomic, strong) UIButton *shopNameBtn;
@property (nonatomic, strong) UILabel *businessLab;
@property (nonatomic, strong) UILabel *storageLab;
@property (nonatomic, strong) UIButton *tipBtn;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) SAHomeMenuListAPI *homeMenuListAPI;
@property (nonatomic, strong) NSMutableArray<SAhomeMenuModel *> *dataMarr;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) SASummaryQueryAPI *summaryQueryAPI;

@property (nonatomic, strong) UILabel *titleLab1;
@property (nonatomic, strong) UILabel *titleLab2;
@property (nonatomic, strong) UILabel *titleLab3;
@property (nonatomic, strong) UILabel *saleNumLab;
@property (nonatomic, strong) UILabel *salePriceLab;
@property (nonatomic, strong) UILabel *profitsLab;
@property (nonatomic, strong) UIView *buleLine;

@property (nonatomic, strong) UIImageView *tipImageV;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSString *count;
@property (nonatomic, strong) NSString *xj;
@property (nonatomic, strong) NSString *profitMargin;
@property (nonatomic, strong) UIButton *eyeBtn;

@property (nonatomic, strong) UIView *tbHeaderview;

@property (nonatomic, strong) UIButton *storeManagementBtn;
@property (nonatomic, strong) UIButton *myAccountBtn;
@property (nonatomic, strong) UIButton *profitBtn;

@property (nonatomic, strong) SACloudPrintHeartbeatAPI *cloudPrintHeartbeatAPI;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) SAUserExpireAPI *userExpireAPI;
@property (nonatomic, strong) SAUserExpireModel *userExpireModel;
@property (nonatomic, strong) SAUserExpireView *userExpireView;

@property (nonatomic, strong) SAOverallSetting *overallSetting;

@property (nonatomic, strong) UIButton *openPayBtn;
@property (nonatomic, strong) UIButton *tipBtn2;
@property (nonatomic, strong) UIView *buleLine2;
@property (nonatomic, strong) UIButton *moreBtn;

@property (nonatomic, strong) NSMutableArray<SACommonProblemsModel *> *qwDataMarr;
@property (nonatomic, strong) SASystemFaqTypeListAPI *systemFaqTypeListAPI;
@property (nonatomic, assign) BOOL isRefresh;

@property (nonatomic, strong) UILabel *tipLab3;
@property (nonatomic, strong) UIView *buleLine3;
@property (nonatomic, strong) UIImageView *entranceImageV;
@property (nonatomic, assign) float showShop;

@property (nonatomic, assign) BOOL isConnection;
@property (nonatomic, assign) NSInteger signal;
@property (nonatomic, assign) NSInteger signal2;
@property (nonatomic, assign) NSInteger signal3;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) UIButton *adBgBtn;
@property (nonatomic, strong) SAActivityListAPI *activityListAPI;
@property (nonatomic, strong) SAExpirationPaymentView *paymentView;
@property (nonatomic, strong) SATrialVersionView *versionView;
@property (nonatomic, strong) SAActivityListModel *activityModel;

@property (nonatomic, strong) SARenewTypeAPI *renewTypeAPI;
@property (nonatomic, strong) NSString *renewType;
@property (nonatomic, strong) NSString *renewUrl;

@property (nonatomic, strong) SAServiceMarketListAPI *serviceMarketListAPI;
@property (nonatomic, strong) SAServiceMarketModel *vipPayModel;//vip支付
@property (nonatomic, strong) SAServiceMarketModel *cloudStorageModel;//云储存
@property (nonatomic, strong) SAServiceMarketView *serviceMarketView;

@property (nonatomic, strong) JXCategoryTitleView *categoryTitleView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong) NSMutableArray<SACategoryView *> *marrCategoryView;
@property (nonatomic, strong) NSMutableArray<SAServiceMarketMenuModel *> *serviceMarr;

@end

@implementation SAHomeVC

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.summaryQueryAPI sendRequestToServerWithActivityViewAndMask:POST];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.overallSetting = [SAOverallSetting shareInstance];
    [self.overallSetting requestByGetOverallSettingWithSuccessBlock:^(id  _Nonnull response) {
    } failBlock:^(NSString * _Nonnull errorMessage) {
    }];
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    [self.tableView.mj_header endRefreshing];
    if (self.summaryQueryAPI == api) {
        self.count = data[@"data"][@"saleStatisticsDAO"][@"count"];//实销数
        self.xj = data[@"data"][@"saleStatisticsDAO"][@"price"];//实销额
        self.profitMargin = data[@"data"][@"saleStatisticsDAO"][@"profitMargin"];//毛利润
        if (self.eyeBtn.isSelected == YES) {
            self.saleNumLab.text = [NSString stringWithFormat:@"%0.lf",[self.count doubleValue]];
            self.salePriceLab.text = [NSString stringWithFormat:@"%0.2lf",[self.xj doubleValue]/100];
            self.profitsLab.text = [NSString stringWithFormat:@"%0.2lf",[self.profitMargin doubleValue]/100];
            
        }else {
            self.saleNumLab.text = @"******";
            self.salePriceLab.text = @"******";
            self.profitsLab.text = @"******";
        }
        
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *statisticsViewOperatingProfit = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"statisticsViewOperatingProfit"]];
        if ([statisticsViewOperatingProfit isEqualToString:@"1"]) {
            self.profitsLab.text = @"******";
        }
        
        NSString *actualSalesAmount = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"actualSalesAmount"]];
        if ([actualSalesAmount isEqualToString:@"1"]) {
            self.salePriceLab.text = @"******";
        }
        
        NSString *str = [NSString stringWithFormat:@"  %@",[SAValueManger shareInStance].userInfo.storeName];
        [_shopNameBtn setTitle:str forState:UIControlStateNormal];
        if (self.isRefresh == YES) {
            self.isRefresh = NO;
            [Prompt popPromptViewWithMsg:@"今日营业数据已刷新" duration:2];
        }
    }else if (self.homeMenuListAPI == api) {
        self.dataMarr = [SAhomeMenuModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        
        //        SAhomeMenuModel *lastModel = self.dataMarr.lastObject;
        //
        //        SAhomeMenuModel *model2 = [SAhomeMenuModel new];
        //        model2.menuId = @"30";
        //        model2.icon = lastModel.icon;
        //        model2.menuName = @"试用版本";
        //        [self.dataMarr addObject:model2];
        //SAMemberMessage
        
        [self.collectionView removeFromSuperview];
        self.collectionView = nil;
        [self.tbHeaderview addSubview:self.collectionView];
        //初始化 pageControl 数量
        NSInteger count = self.dataMarr.count;
        NSInteger pageCount = count%9 == 0 ? (count/9) : (count/9 + 1);
        self.pageControl.numberOfPages = pageCount ;
        self.pageControl.currentPage = 0;
        [self.systemFaqTypeListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }else if (self.userExpireAPI == api) {
        
        //        if ([[SAValueManger shareInStance].userInfo.userName isEqualToString:@"13728761589"]) {
        //            return;
        //        }
        //先弹续费，然后弹会员支付，最后弹活动页面
        self.userExpireModel = [SAUserExpireModel mj_objectWithKeyValues:data[@"data"]];
        if ([self.userExpireModel.needBuy isEqualToString:@"1"]) {
            if ([self.userExpireModel.termType isEqualToString:@"2"] || [self.userExpireModel.termType isEqualToString:@"3"]) {
                [self showTrialVersionView];
            }else {
                if ([SAValueManger shareInStance].userInfo.isMarketingOpen.integerValue != 1) {
                    [self.activityListAPI sendRequestToServerWithType:POST];
                }
            }
        }else {
            if ([self.userExpireModel.termType isEqualToString:@"2"] || [self.userExpireModel.termType isEqualToString:@"3"]) {
                [self showExpirationPaymentView];
            }else {
                if ([SAValueManger shareInStance].userInfo.isMarketingOpen.integerValue != 1) {
                    [self.activityListAPI sendRequestToServerWithType:POST];
                }
            }
        }
        [self.serviceMarketListAPI sendRequestToServerWithType:GET];//获取会员活动信息
    }else if (self.systemFaqTypeListAPI == api) {
        
        self.qwDataMarr = [SACommonProblemsModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self.tableView reloadData];
        
    }else if (self.activityListAPI == api) {
        NSMutableArray<SAActivityListModel *> *marr = [SAActivityListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (marr.count == 0) return;
        
        SAActivityListModel *activityModel = marr.firstObject;
        self.activityModel = activityModel;
        if ([SAValueManger shareInStance].userInfo.userType == 1) {
            if ([self getDifferenceByDate:activityModel.endTime] < 0) {
                return;
            }
            //            [0]    (null)    @"iosDstViewUri" : @"openPay"
            UIButton *adBgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            self.adBgBtn = adBgBtn;
            adBgBtn.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            adBgBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
            [[UIApplication sharedApplication].keyWindow addSubview:adBgBtn];
            [adBgBtn addTarget:self action:@selector(clickedAdBgBtn) forControlEvents:UIControlEventTouchUpInside];
            
            UIImageView *adImageV = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - kScaleNum(345))/2, (kScreenHeight - kScaleNum(412))/2, kScaleNum(345), kScaleNum(412))];
            //                adImageV.image = [UIImage imageNamed:@"home_ad"];
            [adImageV sd_setImageWithURL:[NSURL URLWithString:activityModel.coverUrl]];
            [adBgBtn addSubview:adImageV];
            adImageV.userInteractionEnabled = YES;
            UITapGestureRecognizer *adImageVTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adImageVTapEvent)];
            [adImageV addGestureRecognizer:adImageVTap];
        }
    }else if (self.renewTypeAPI == api) {
        self.renewType = [NSString stringWithFormat:@"%@",data[@"data"][@"renewType"]];
        self.renewUrl = [NSString stringWithFormat:@"%@",data[@"data"][@"renewUrl"]];
    }else if (self.serviceMarketListAPI == api) {
        NSMutableArray<SAServiceMarketMenuModel *> *marr = [SAServiceMarketMenuModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        self.serviceMarr = marr;
        NSMutableArray *titleMarr = [NSMutableArray array];
        for (SAServiceMarketMenuModel *marketModel in marr) {
            [titleMarr addObject:marketModel.menuName];
            for (SAServiceMarketModel *model in marketModel.children) {
                if ([model.menuCode isEqualToString:@"pay_vip"]) {
                    self.vipPayModel = model;
                }
                if ([model.menuCode isEqualToString:@"cloud_set_meal"]) {
                    self.cloudStorageModel = model;
                }
            }
        }
        
        if (titleMarr.count > 0) {
            self.marrCategoryView = [NSMutableArray array];
            for (int i = 0; i < titleMarr.count; i++) {
                SACategoryView *view = [[SACategoryView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(90))];
                [self.marrCategoryView addObject:view];
            }
            self.categoryTitleView.titles = titleMarr;
            [self.categoryTitleView reloadData];
        }
        
        if ([SAValueManger shareInStance].userInfo.isMarketingOpen.integerValue == 1) {
            
            if (!([self.userExpireModel.termType isEqualToString:@"2"] || [self.userExpireModel.termType isEqualToString:@"3"])) {
                [self showServiceMarketView];
            }
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.summaryQueryAPI == api) {
        [self.tableView.mj_header endRefreshing];
    }
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"SAIndexCell";
    SAIndexCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.model = self.dataMarr[indexPath.row];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SAhomeMenuModel *model = self.dataMarr[indexPath.row];
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *isShopSale = [NSString stringWithFormat:@"%@",menuList[0][@"isDelete"]];
    
    NSString *isShopPreview = [NSString stringWithFormat:@"%@",menuList[1][@"isDelete"]];
    NSString *productPrintLabel = [NSString stringWithFormat:@"%@",menuList[1][@"perms"][@"productPrintLabel"]];
    
    NSString *isWarehousing = [NSString stringWithFormat:@"%@",menuList[2][@"isDelete"]];
    NSString *purchaseOfGoods = [NSString stringWithFormat:@"%@",menuList[2][@"perms"][@"purchaseOfGoods"]];
    
    NSString *inventory = [NSString stringWithFormat:@"%@",menuList[3][@"isDelete"]];
    NSString *stockNewInventory = [NSString stringWithFormat:@"%@",menuList[3][@"perms"][@"stockNewInventory"]];
    
    NSString *isReturnGoods = [NSString stringWithFormat:@"%@",menuList[5][@"isDelete"]];
    
    NSString *isVipManagement = [NSString stringWithFormat:@"%@",menuList[6][@"isDelete"]];
    
    NSString *isSupplier = [NSString stringWithFormat:@"%@",menuList[7][@"isDelete"]];
    NSString *seeProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"seeProvider"]];
    
    NSString *isStaffManagement = [NSString stringWithFormat:@"%@",menuList[9][@"isDelete"]];
    NSString *systemSettingEmpManageView = [NSString stringWithFormat:@"%@",menuList[9][@"perms"][@"systemSettingEmpManageView"]];
    
    NSString *isSaveDispatch = [NSString stringWithFormat:@"%@",menuList[10][@"isDelete"]];
    NSString *saveDispatch = [NSString stringWithFormat:@"%@",menuList[10][@"perms"][@"saveDispatch"]];
    
    //https://saas.fuyungroup.com/micro-store/#/?token=ed46c44a6328493b88cdbcdc867d680e&merchantId=10
    NSString *weiShopUrl = [NSString stringWithFormat:@"https://saas.fuyungroup.com/micro-store/#/?token=%@&merchantId=%zd",[SAValueManger shareInStance].userInfo.token,[SAValueManger shareInStance].userInfo.merchantId];
    
    NSString *testWeiShopUrl = [NSString stringWithFormat:@"http://192.168.0.172:8080?token=%@&merchantId=%zd",[SAValueManger shareInStance].userInfo.token,[SAValueManger shareInStance].userInfo.merchantId];
    
    NSString *fullSubtractionUrl = [NSString stringWithFormat:@"https://saas.fuyungroup.com/marketing/#/?token=%@",[SAValueManger shareInStance].userInfo.token];
    
    switch (model.menuId.integerValue) {
        case 1://销售开单
            if ([isShopSale isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有销售开单权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAShopSaleVC new] animated:YES];
            break;
        case 2://上传商品
            if ([isShopPreview isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有商品权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAShopPreviewVC new] animated:YES];
            break;
        case 3://商品入库
            if ([isWarehousing isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有入库权限,请联系店长添加" duration:2];
                break;
            }else if ([purchaseOfGoods isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有商品入库权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAWarehousingVC new] animated:YES];
            break;
        case 4://标签打印
            if ([productPrintLabel isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有打印标签权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAPrintLableVC new] animated:YES];
            break;
        case 5://盘点单
            if ([inventory isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有库存权限,请联系店长添加" duration:2];
                break;
            }else if ([stockNewInventory isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有新增盘点权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAAddInventoryVC new] animated:YES];
            break;
        case 6://订单退货
            if ([isReturnGoods isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有退货权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAReturnGoodsVC new] animated:YES];
            break;
        case 7://会员管理
            if ([isVipManagement isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有会员权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAVipManagementVC new] animated:YES];
            break;
        case 8://供货商
            if ([isSupplier isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
                break;
            }
            if ([seeProvider isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有供货商权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SASupplierVC new] animated:YES];
            break;
        case 9://员工管理
            if ([isStaffManagement isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有设置权限,请联系店长添加" duration:2];
                break;
            }else if ([systemSettingEmpManageView isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有员工管理权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAStaffManagementVC new] animated:YES];
            break;
        case 10://新手教程
            [self.navigationController pushViewController:[SATutorialVC new] animated:YES];
            break;
        case 11://收款
            [self.navigationController pushViewController:[SACollectionPayVC new] animated:YES];
            break;
        case 12://调货
            if ([isSaveDispatch isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有调配货权限,请联系店长添加" duration:2];
                break;
            }else if ([saveDispatch isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有新增调配货权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[[SAShopAllocateVC alloc] initWithType:@"2"] animated:YES];
            break;
        case 13://配货
            if ([isSaveDispatch isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有调配货权限,请联系店长添加" duration:2];
                break;
            }else if ([saveDispatch isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有新增调配货权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[[SAShopAllocateVC alloc] initWithType:@"1"] animated:YES];
            break;
        case 14://商品退货
            if ([isReturnGoods isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有退货权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAShopReturnGoodsVC new] animated:YES];
            break;
        case 15://微店
            [self.navigationController pushViewController:[[SAShopWKWebVC alloc] initWithTitle:@"微店" AndUrl:weiShopUrl] animated:YES];
            break;
        case 1001://测试
            [self.navigationController pushViewController:[[SAShopWKWebVC2 alloc] initWithTitle:@"微店" AndUrl:testWeiShopUrl] animated:YES];
            break;
        case 16://小票入库
            [self.navigationController pushViewController:[SABatchPurchaseVC new] animated:YES];
            break;
        case 17://会员充值记录
            if ([isVipManagement isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"您没有会员权限,请联系店长添加" duration:2];
                break;
            }
            [self.navigationController pushViewController:[SAMemberTopUpRecordVC new] animated:YES];
            break;
        case 18://会员短信
            [self.navigationController pushViewController:[SAMemberMessageVC new] animated:YES];
            break;
        case 19://满减
            [self.navigationController pushViewController:[[SAShopWKWebVC alloc] initWithTitle:@"满减" AndUrl:fullSubtractionUrl] animated:YES];
            break;
        default:
            [Prompt popPromptViewWithMsg:@"该功能暂未开放，敬请期待" duration:2];
            break;
    };
}

- (void)scrollViewDidScroll:(UIScrollView *)sender{
    int page = _collectionView.contentOffset.x/kScreenWidth;
    _pageControl.currentPage = page;
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.qwDataMarr.count > 3) {
        return 3;
    }
    return self.qwDataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SACommonProblemsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SACommonProblemsCell" forIndexPath:indexPath];
    cell.model = self.qwDataMarr[indexPath.section];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SACommonProblemsDetailVC *pushVC = [[SACommonProblemsDetailVC alloc] initWithProblemsModel:self.qwDataMarr[indexPath.section]];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(1);
}

#pragma mark - CategoryView Delegate
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.serviceMarr.count;
}

- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    WeakSelf
    SACategoryView *view = self.marrCategoryView[index];
    view.model = self.serviceMarr[index];
    view.marketBlock = ^(SAServiceMarketModel *marketModel) {
        [weakSelf clickService:marketModel];
    };
    return view;
}

#pragma mark - event
-(void)ExitLogin {
    [SAValueManger shareInStance].userInfo = nil;
    [kUserDefault setObject:@"" forKey:kPasswordKey];
    UIWindow *window =  [UIApplication sharedApplication].keyWindow;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[SALoginVC new]];
    window.rootViewController = nav;
    [window makeKeyAndVisible];
}

- (void)clickExitBtn {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定退出当前账号？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
        [self ExitLogin];
    }];
    UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:true completion:nil];
}

-(void)clickedEyeBtn:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    if (sender.isSelected == YES) {
        self.saleNumLab.text = [NSString stringWithFormat:@"%0.lf",[self.count doubleValue]];
        self.salePriceLab.text = [NSString stringWithFormat:@"%0.2lf",[self.xj doubleValue]/100];
        self.profitsLab.text = [NSString stringWithFormat:@"%0.2lf",[self.profitMargin doubleValue]/100];
        [kUserDefault setObject:@"1" forKey:kEyeKey];
    }else {
        self.saleNumLab.text = @"******";
        self.salePriceLab.text = @"******";
        self.profitsLab.text = @"******";
        [kUserDefault setObject:@"" forKey:kEyeKey];
    }
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *statisticsViewOperatingProfit = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"statisticsViewOperatingProfit"]];
    if ([statisticsViewOperatingProfit isEqualToString:@"1"]) {
        self.profitsLab.text = @"******";
    }
    
    NSString *actualSalesAmount = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"actualSalesAmount"]];
    if ([actualSalesAmount isEqualToString:@"1"]) {
        self.salePriceLab.text = @"******";
    }
}

-(void)clickedTipImageV {
    SAMarketingVC *pushVC = [SAMarketingVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedStoreManagementBtn {
    SAStoreManagementVC *pushVC = [[SAStoreManagementVC alloc] init];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedMyAccountBtn {
    SAMyAccountVC *pushVC = [[SAMyAccountVC alloc] init];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedProfitBtn {
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *statisticsViewOperatingProfit = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"statisticsViewOperatingProfit"]];
    if ([statisticsViewOperatingProfit isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有营业利润权限,请联系店长添加" duration:2];
        return;
    }
    
    NSString *actualSalesAmount = [NSString stringWithFormat:@"%@",menuList[8][@"perms"][@"actualSalesAmount"]];
    if ([actualSalesAmount isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有实销额权限,请联系店长添加" duration:2];
        return;
    }
    
    SAOperatingProfitVC *pushVC = [[SAOperatingProfitVC alloc] init];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)timerFired {
    if ([SAOverallSetting shareInstance].printerSetting.printerStatus == 2) {
        if (kIsTestServer == 1) {
            self.cloudPrintHeartbeatAPI.deviceToken = kDeviceToken;
            self.cloudPrintHeartbeatAPI.deviceType = @"2";
            self.cloudPrintHeartbeatAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
            self.cloudPrintHeartbeatAPI.os = @"2";
            self.cloudPrintHeartbeatAPI.printerType = 1;
            if ([SAValueManger shareInStance].printType == 2) {
                self.cloudPrintHeartbeatAPI.printerType = 2;
            }
            [self.cloudPrintHeartbeatAPI submitForm:POST];
        }
    }
}

-(void)removeUserExpireView {
    self.userExpireView = nil;
}

-(void)significantTimeChange {
    [self.userExpireAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedOpenPayBtn {
    [self.navigationController pushViewController:[SAOpenPayVC new] animated:YES];
}

-(void)clickedMoreBtn {
    [self.navigationController pushViewController:[SACommonProblemsVC new] animated:YES];
}

-(void)clickedAdBgBtn {
    [self.adBgBtn removeFromSuperview];
}

-(void)adImageVTapEvent {
    [MobClick event:@"btn_active_openpay"];//统计广告点击数
    if ([self.activityModel.dstViewType isEqualToString:@"0"]) {
        if ([self.activityModel.iosDstViewUri isEqualToString:@"openPay"]) {
            [self.navigationController pushViewController:[SAOpenPayVC new] animated:YES];
        }else if ([self.activityModel.iosDstViewUri isEqualToString:@"inventory"]) {
            HDTabBarController *vc = (HDTabBarController *)self.navigationController.viewControllers[0];
            [vc setSelectIndex:1];
        }else if ([self.activityModel.iosDstViewUri isEqualToString:@"wxShop"]) {
            NSString *weiShopUrl = [NSString stringWithFormat:@"https://saas.fuyungroup.com/micro-store/#/?token=%@&merchantId=%zd",[SAValueManger shareInStance].userInfo.token,[SAValueManger shareInStance].userInfo.merchantId];
            [self.navigationController pushViewController:[[SAShopWKWebVC alloc] initWithTitle:@"微店" AndUrl:weiShopUrl] animated:YES];
        }else if ([self.activityModel.iosDstViewUri isEqualToString:@"batchPurchase"]) {
            [self.navigationController pushViewController:[SABatchPurchaseVC new] animated:YES];
        }else if ([self.activityModel.iosDstViewUri isEqualToString:@"memberMessage"]) {
            [self.navigationController pushViewController:[SAMemberMessageVC new] animated:YES];
        }
    }
    
    [self.adBgBtn removeFromSuperview];
}

-(void)clickedEntranceImageV {
    //测试使用
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = @"gh_146cb32ec7ad";
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease;
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        
    }];
    //
    //    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    //    launchMiniProgramReq.userName = @"gh_2fa987492152";
    //    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease;
    //    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
    //
    //    }];
    
    
    //    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
    //        [Prompt popPromptViewWithMsg:@"进入分享2" duration:2];
    //        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    //        req.scene = WXSceneSession;
    //        WXMediaMessage *message = [WXMediaMessage message];
    //        message.title = @"衣点通";
    //        message.description = @"";
    //
    ////        [message setThumbData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dic[@"imageUrl"]]]];
    //
    //        WXWebpageObject *webObj = [WXWebpageObject object];
    //        webObj.webpageUrl = @"";
    //        message.mediaObject = webObj;
    //        req.message = message;
    //        [WXApi sendReq:req completion:^(BOOL success) {
    //            NSLog(@"打开微信小程序:%@", success ? @"成功" : @"失败");
    //        }];
    //    }
}

-(void)showTrialVersionView {
    
    SATrialVersionView *versionView = [[SATrialVersionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) AndModel:self.userExpireModel];
    self.versionView = versionView;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:versionView];
    WeakSelf
    versionView.payBlock = ^{
        [weakSelf pushTrialVersionVC];
    };
}

-(void)showServiceMarketView{
    
    SAServiceMarketView *serviceMarketView = [[SAServiceMarketView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) AndModel:self.vipPayModel];
    self.serviceMarketView = serviceMarketView;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:serviceMarketView];
    WeakSelf
    serviceMarketView.payBlock = ^{
        [weakSelf clickVipCell];
    };
}

-(void)pushTrialVersionVC {
    NSString *url = [NSString stringWithFormat:@"https://saas.fuyungroup.com/growth/software_purchase.html?dueDate=%@&registDate=%@",self.userExpireModel.dueDate,self.userExpireModel.registDate];
    
    if ([self.renewType isEqualToString:@"1"]) {
        // 构建淘宝客户端协议的 URL
        url = self.renewUrl;
        
        NSString *openUrl = [self.renewUrl stringByReplacingOccurrencesOfString:@"https://" withString:@"taobao://"];
        openUrl = [openUrl stringByReplacingOccurrencesOfString:@"http://" withString:@"taobao://"];
        // 判断当前系统是否有安装淘宝客户端
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]]) {
            // 如果已经安装淘宝客户端，就使用客户端打开链接
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:[NSDictionary dictionary] completionHandler:nil];
            return;
        }
    }
    
    SAPaymentWKWebVC *webVC = [[SAPaymentWKWebVC alloc] initWithTitle:@"支付" AndUrl:url];
    self.versionView.hidden = YES;
    [self.navigationController pushViewController:webVC animated:YES];
    WeakSelf
    webVC.successedBlock = ^(NSString * _Nonnull status) {
        if ([status isEqualToString:@"1"]) {
            [weakSelf.versionView removeFromSuperview];
        }else {
            weakSelf.versionView.hidden = NO;
        }
    };
}

-(void)showExpirationPaymentView {
    SAExpirationPaymentView *paymentView = [[SAExpirationPaymentView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) AndModel:self.userExpireModel];
    self.paymentView = paymentView;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:paymentView];
    WeakSelf
    paymentView.payBlock = ^{
        [weakSelf clickCloudCell];
    };
}

-(void)pushExpirationPaymentVC {
    
    NSString *url = [NSString stringWithFormat:@"https://saas.fuyungroup.com/growth/software_renewal.html?dueDate=%@&registDate=%@",self.userExpireModel.dueDate,self.userExpireModel.registDate];
    
    if ([self.renewType isEqualToString:@"1"]) {
        // 构建淘宝客户端协议的 URL
        url = self.renewUrl;
        
        NSString *openUrl = [self.renewUrl stringByReplacingOccurrencesOfString:@"https://" withString:@"taobao://"];
        openUrl = [openUrl stringByReplacingOccurrencesOfString:@"http://" withString:@"taobao://"];
        // 判断当前系统是否有安装淘宝客户端
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:openUrl]]) {
            // 如果已经安装淘宝客户端，就使用客户端打开链接
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:[NSDictionary dictionary] completionHandler:nil];
            return;
        }
    }
    
    SAPaymentWKWebVC *webVC = [[SAPaymentWKWebVC alloc] initWithTitle:@"支付" AndUrl:url];
    self.paymentView.hidden = YES;
    [self.navigationController pushViewController:webVC animated:YES];
    WeakSelf
    webVC.successedBlock = ^(NSString * _Nonnull status) {
        if ([status isEqualToString:@"1"]) {
            [weakSelf.paymentView removeFromSuperview];
        }else {
            weakSelf.paymentView.hidden = NO;
        }
    };
}

-(void)forceOpenPay {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"message:@"基本信息注册完成,请开通支付后才能使用！" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"下一步" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self clickedOpenPayBtn];
    }]];
}

-(void)clickVipCell {
    NSDictionary *dic = @{@"info" : [SAValueManger shareInStance].userInfo.token, @"storeName" : [SAValueManger shareInStance].userInfo.storeName};
    NSString* storeName = [[SAValueManger shareInStance].userInfo.storeName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSString *url = [NSString stringWithFormat:@"%@?token=%@&storeName=%@",self.vipPayModel.jumpLink,[SAValueManger shareInStance].userInfo.token,storeName];
    
    SAOpenVipWKWebVC *webVC = [[SAOpenVipWKWebVC alloc] initWithUrl:url AndDataDic:dic];
    webVC.view.backgroundColor = [UIColor blackColor];
    [self.navigationController pushViewController:webVC animated:YES];
    WeakSelf
    webVC.successedBlock = ^(NSString * _Nonnull status) {
        if ([status isEqualToString:@"1"]) {
            [SAValueManger shareInStance].userInfo.isVip = @"1";
            weakSelf.vipImageV.image = [UIImage imageNamed:@"vip_act"];
        }
    };
}

-(void)clickCloudCell {
    NSDictionary *dic = @{@"info" : [SAValueManger shareInStance].userInfo.token, @"storeName" : [SAValueManger shareInStance].userInfo.storeName};
    NSString* storeName = [[SAValueManger shareInStance].userInfo.storeName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSString *url = [NSString stringWithFormat:@"%@&token=%@&storeName=%@",self.cloudStorageModel.jumpLink,[SAValueManger shareInStance].userInfo.token,storeName];
    SAOpenVipWKWebVC *webVC = [[SAOpenVipWKWebVC alloc] initWithUrl:url AndDataDic:dic];
    webVC.view.backgroundColor = kColor(244, 64, 55, 1);
    self.paymentView.hidden = YES;
    [self.navigationController pushViewController:webVC animated:YES];
    WeakSelf
    webVC.successedBlock = ^(NSString * _Nonnull status) {
        if ([status isEqualToString:@"1"]) {
            [weakSelf.paymentView removeFromSuperview];
        }else {
            weakSelf.paymentView.hidden = NO;
        }
    };
}

-(void)clickService:(SAServiceMarketModel *)model {
    if ([model.menuCode isEqualToString:@"pay_vip"]) {
        [self clickVipCell];
    } else if ([model.menuCode isEqualToString:@"cloud_set_meal"]) {
        [self clickCloudCell];
    } else {
        NSDictionary *dic = @{@"info" : [SAValueManger shareInStance].userInfo.token, @"storeName" : [SAValueManger shareInStance].userInfo.storeName};
        NSString* storeName = [[SAValueManger shareInStance].userInfo.storeName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSString *jumpLink = model.jumpLink;
        NSString *url = @"";
        if ([jumpLink containsString:@"?"]) {
            url = [NSString stringWithFormat:@"%@&token=%@&storeName=%@",jumpLink,[SAValueManger shareInStance].userInfo.token,storeName];
        } else {
            url = [NSString stringWithFormat:@"%@?token=%@&storeName=%@",jumpLink,[SAValueManger shareInStance].userInfo.token,storeName];
        }
        SAOpenVipWKWebVC *webVC = [[SAOpenVipWKWebVC alloc] initWithUrl:url AndDataDic:dic];
        webVC.view.backgroundColor = kColor(117, 139, 238, 1);;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

#pragma mark - loadData
-(void)loadData {
    
    SAUserInfo *model = [SAValueManger shareInStance].userInfo;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    self.summaryQueryAPI.merchantId = @(model.merchantId).stringValue;
    self.summaryQueryAPI.storeId = @(model.storeInfo.storeId).stringValue;
    self.summaryQueryAPI.startTime = timeFormatStr;
    self.summaryQueryAPI.endTime = timeFormatStr;
    [self.summaryQueryAPI sendRequestToServerWithActivityViewAndMask:POST];
}


-(NSString *)stringToAsci:(NSString *)string {
    NSMutableString *mustring = [[NSMutableString alloc]init];
    
    for (NSInteger i = 0; i < string.length; i++) {
               unichar c = [string characterAtIndex:i];
               int ascii = (int)c;
               [mustring appendFormat:@"\\u%c", ascii];
    }
    return mustring;
    
//    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//    const char *ch = [data bytes];
//    NSInteger len = [data length];
//    for (int i = 0; i < len; i++) {
//        [mustring appendString:[NSString stringWithFormat:@"%c",ch[i]]];
//    }
//    return mustring;
}

#pragma mark - initUI
-(void)initUI {
    self.view.backgroundColor = kColor(246, 246, 246, 1);
    self.showShop = -120;
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.topImageV2];
    self.tableView.tableHeaderView = self.tbHeaderview;
    self.tbHeaderview.backgroundColor = kColor(246, 246, 246, 1);
    
    [self.tbHeaderview addSubview:self.topImageV];
    [self.tbHeaderview addSubview:self.whiteImageV];
    
    [self.whiteImageV addSubview:self.businessLab];
    [self.whiteImageV addSubview:self.titleLab1];
    [self.whiteImageV addSubview:self.titleLab2];
    [self.whiteImageV addSubview:self.titleLab3];
    [self.whiteImageV addSubview:self.saleNumLab];
    [self.whiteImageV addSubview:self.salePriceLab];
    [self.whiteImageV addSubview:self.profitsLab];
    
    [self.tbHeaderview addSubview:self.buleLine];
    [self.tbHeaderview addSubview:self.headerImageV];
    [self.tbHeaderview addSubview:self.userNameLab];
    [self.tbHeaderview addSubview:self.vipImageV];
    [self.tbHeaderview addSubview:self.shopNameBtn];
    [self.tbHeaderview addSubview:self.storageLab];
    [self.tbHeaderview addSubview:self.tipBtn];
    [self.tbHeaderview addSubview:self.tipBtn2];
    [self.tbHeaderview addSubview:self.buleLine2];
    [self.tbHeaderview addSubview:self.moreBtn];

    //    [self.tbHeaderview addSubview:self.entranceImageV];
    
    [self.userNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(48 + DifferenceHeight));
        make.left.mas_equalTo(kScaleNum(95));
        make.height.mas_equalTo(kScaleNum(20));
    }];
    
    [self.vipImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(kScaleNum(48 + DifferenceHeight));
        make.left.mas_equalTo(self.userNameLab.mas_right).offset(2);
        make.width.mas_equalTo(kScaleNum(16));
        make.height.mas_equalTo(kScaleNum(16));
    }];
    
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, kScaleNum(515 + DifferenceHeight), kScreenWidth, kScaleNum(20))];
    pageControl.numberOfPages = 1;
    pageControl.currentPage = 0;
    pageControl.currentPageIndicatorTintColor = kBuleColor;
    pageControl.pageIndicatorTintColor = kColor(230, 230, 230, 1);
    pageControl.hidesForSinglePage = YES;
    self.pageControl = pageControl;
    pageControl.backgroundColor = [UIColor whiteColor];
    [self.tbHeaderview addSubview:self.pageControl];
    if ([SAValueManger shareInStance].noServiceMarket != YES) {
//        [self.tbHeaderview addSubview:self.tipLab3];
//        [self.tbHeaderview addSubview:self.buleLine3];
        [self.tbHeaderview addSubview:self.tipImageV];
        [self.tbHeaderview addSubview:self.categoryTitleView];
        self.categoryTitleView.titles = @[];
        self.categoryTitleView.titleColorGradientEnabled = YES;
        self.categoryTitleView.averageCellSpacingEnabled = NO;
        self.categoryTitleView.contentEdgeInsetLeft = 20;
        
        self.listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
        self.listContainerView.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(90));
        [self.tipImageV addSubview:self.listContainerView];
        // 关联到 categoryView
        self.categoryTitleView.listContainer = self.listContainerView;
    }
    
    [self.tbHeaderview addSubview:self.eyeBtn];
    if ([[SAValueManger shareInStance].userInfo.empType isEqualToString:@"1"]) {
        if (![[SAValueManger shareInStance].userInfo.auditStatus isEqualToString:@"1"]) {
            [self.tbHeaderview addSubview:self.openPayBtn];
        }
    }
    [self.tbHeaderview addSubview:self.storeManagementBtn];
    [self.tbHeaderview addSubview:self.profitBtn];
    [self.tbHeaderview addSubview:self.myAccountBtn];
    
    NSString *eye = kEye;
    self.eyeBtn.selected = eye.length > 0;
    
    
    //    UIRefreshControl *control = [[UIRefreshControl alloc] init];
    //    [control addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
    //    self.control = control;
    //    //不用自定义frame
    //    [self.tableView addSubview:control];
    
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.isRefresh = YES;
        [weakSelf loadData];
    }];
    
    [self.homeMenuListAPI sendRequestToServerWithActivityViewAndMask:GET];
    self.isRefresh = NO;
    [self loadData];
    
    [self bleConnecter]; //自动连接打印机
    //启动心跳
    [self timerFired];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    
    NSString *openPayment = kRegisteredOpenPayment;
    if ([openPayment isEqualToString:@"1"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:kRegisteredOpenPaymentKey];
        //    // 延迟1秒执行：
        double delayInSeconds = 1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self clickedOpenPayBtn];
        });
    }else if ([[SAValueManger shareInStance].userInfo.forceOpenPay isEqualToString:@"1"]) {
        double delayInSeconds = 1;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self forceOpenPay];
        });
    }else {
        [self.userExpireAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
    
    [self.renewTypeAPI sendRequestToServerWithType:POST];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(significantTimeChange) name:UIApplicationSignificantTimeChangeNotification object:nil];
}

-(void)shownewStatus:(int)count
{
    //首先将label控件隐藏在导航栏的后面
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height+self.navigationController.navigationBar.frame.size.height-35, [UIScreen mainScreen].bounds.size.width, 35);
    label.backgroundColor = [UIColor orangeColor];
    if(count == 0){
        label.text = @"没有最新的微博数据";
    }else{
        //count是传进来的数量
        label.text = [NSString stringWithFormat:@"已加载%d条最新的微博数据",count];
    }
    label.textColor = [UIColor whiteColor];
    //设置文字居中
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16.0];
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    //动画显示
    [UIView animateWithDuration:1.0 animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, 35);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
            //一键回到最初的状态
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            //不用的时候把label移除掉
            [label removeFromSuperview];
        }];
    }];
}

//获取日期相差时间
- (NSInteger)getDifferenceByDate:(NSString *)date {
    //获得当前时间
    NSDate *now = [NSDate date];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    NSString *nowDateStr = [dateFormatter stringFromDate:now];
    NSDate *nowDate = [dateFormatter dateFromString:nowDateStr];
    
    NSDate *oldDate = [dateFormatter dateFromString:date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned int unitFlags =NSCalendarUnitDay;
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:nowDate toDate:oldDate options:0];
    return [comps day];
}

-(UIImageView *)topImageV {
    if (!_topImageV) {
        _topImageV = [[UIImageView alloc] initWithFrame:SARectMake(0, 0, 375, 170 + DifferenceHeight)];
        _topImageV.image = [UIImage imageNamed:@"home_topBg"];
    }
    return _topImageV;
}

-(UIImageView *)topImageV2 {
    if (!_topImageV2) {
        _topImageV2 = [[UIImageView alloc] initWithFrame:SARectMake(0, 0, 375, 30 + DifferenceHeight)];
        _topImageV2.image = [UIImage imageNamed:@"home_topBg"];
        _topImageV2.contentMode = UIViewContentModeScaleToFill;
//        _topImageV2.clipsToBounds = YES;
    }
    return _topImageV2;
}

-(UIImageView *)whiteImageV {
    if (!_whiteImageV) {
        _whiteImageV = [[UIImageView alloc] initWithFrame:SARectMake(15, 125 + DifferenceHeight, 345, 90)];
        _whiteImageV.backgroundColor = [UIColor whiteColor];
        _whiteImageV.layer.cornerRadius = kScaleNum(6);
        _whiteImageV.layer.masksToBounds = YES;
        _whiteImageV.userInteractionEnabled = YES;
    }
    return _whiteImageV;
}
-(UIImageView *)headerImageV {
    if (!_headerImageV) {
        _headerImageV = [[UIImageView alloc] initWithFrame:CGRectMake(kScaleNum(36), kScaleNum(43 + DifferenceHeight), kScaleNum(50), kScaleNum(50))];
        _headerImageV.image = [UIImage imageNamed:@"home_headerImage"];
        _headerImageV.layer.cornerRadius = kScaleNum(25);
        _headerImageV.layer.masksToBounds = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickExitBtn)];
        [_headerImageV addGestureRecognizer:tap];
        _headerImageV.userInteractionEnabled = YES;
    }
    return _headerImageV;
}

-(UILabel *)userNameLab {
    if (!_userNameLab) {
        _userNameLab = [[UILabel alloc] init];
        SAUserInfo *model = [SAValueManger shareInStance].userInfo;
        NSString *name = model.empName;
        NSString *position = @"(老板)";
        if ([SAValueManger shareInStance].userInfo.userType == 2) {
            position = @"(店长)";
        }else if ([SAValueManger shareInStance].userInfo.userType == 3) {
            position = @"(营业员)";
        }else if ([SAValueManger shareInStance].userInfo.userType == 4) {
            position = @"(收银员)";
        }
        _userNameLab.text = [name stringByAppendingString:position];
        _userNameLab.textColor = [UIColor whiteColor];
        _userNameLab.textAlignment = NSTextAlignmentLeft;
        _userNameLab.font = kBFont(15);
    }
    return _userNameLab;
}

-(UIImageView *)vipImageV {
    if (!_vipImageV) {
        _vipImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"vip_nor"]];
        if ([SAValueManger shareInStance].userInfo.isVip.integerValue == 1)  {
            _vipImageV.image = [UIImage imageNamed:@"vip_act"];
        }
    }
    return _vipImageV;
}

-(UIButton *)shopNameBtn {
    if (!_shopNameBtn) {
        _shopNameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shopNameBtn setImage:[UIImage imageNamed:@"home_store"] forState:UIControlStateNormal];
        NSString *str = [NSString stringWithFormat:@"  %@",[SAValueManger shareInStance].userInfo.storeName];
        [_shopNameBtn setTitle:str forState:UIControlStateNormal];
        [_shopNameBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _shopNameBtn.frame = CGRectMake(kScaleNum(95), kScaleNum(61 + DifferenceHeight), kScaleNum(260), kScaleNum(40));
        _shopNameBtn.titleLabel.font = kFont(13);
        _shopNameBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _shopNameBtn.userInteractionEnabled = YES;
    }
    return _shopNameBtn;
}

-(UILabel *)businessLab {
    if (!_businessLab) {
        _businessLab = [[UILabel alloc] initWithFrame:SARectMake(0, 15, 345, 15)];
        _businessLab.text = @"今日营业";
        _businessLab.textColor = kBlackColor;
        _businessLab.font = kBFont(15);
        _businessLab.textAlignment = NSTextAlignmentCenter;
    }
    return _businessLab;
}

-(UILabel *)storageLab {
    if (!_storageLab) {
        _storageLab = [[UILabel alloc] initWithFrame:CGRectMake(0, kScaleNum(190 + DifferenceHeight), kScreenWidth, kScaleNum(15))];
        _storageLab.textColor = kGrayColor;
        _storageLab.font = kFont(14);
        _storageLab.textAlignment = NSTextAlignmentCenter;
    }
    return _storageLab;
}

-(UIButton *)tipBtn {
    if (!_tipBtn) {
        _tipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tipBtn setTitle:@"常用功能" forState:UIControlStateNormal];
        [_tipBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        _tipBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _tipBtn.titleLabel.font = kFont(14);
        _tipBtn.frame = SARectMake(25, 230 + DifferenceHeight, 200, 14);
        _tipBtn.userInteractionEnabled = NO;
    }
    return _tipBtn;
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        SAIndexFlowLayout *flowLayout = [SAIndexFlowLayout new];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.dataList = self.dataMarr;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kScaleNum(258 + DifferenceHeight), kScreenWidth, kScaleNum(257)) collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = NO;
        [_collectionView registerClass:[SAIndexCell class] forCellWithReuseIdentifier:@"SAIndexCell"];
    }
    return _collectionView;
}

-(UIButton *)tipBtn2 {
    if (!_tipBtn2) {
        long y = 0;
        if ([SAValueManger shareInStance].noServiceMarket == YES) {
            y = -130;
        }
        _tipBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tipBtn2 setTitle:@"常见功能" forState:UIControlStateNormal];
        [_tipBtn2 setTitleColor:kBlackColor forState:UIControlStateNormal];
        _tipBtn2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _tipBtn2.titleLabel.font = kFont(14);
        _tipBtn2.frame = SARectMake(25, 801 + DifferenceHeight + self.showShop + y, 200, 14);
        _tipBtn2.userInteractionEnabled = NO;
    }
    return _tipBtn2;
}

-(UIButton *)moreBtn {
    if (!_moreBtn) {
        long y = 0;
        if ([SAValueManger shareInStance].noServiceMarket == YES) {
            y = -130;
        }
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _moreBtn.frame = CGRectMake(0, kScaleNum(787 + DifferenceHeight + self.showShop + y) , kScreenWidth, kScaleNum(42));
        [_moreBtn setTitle:@"更多>>" forState:UIControlStateNormal];
        [_moreBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        _moreBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _moreBtn.titleLabel.font = kFont(14);
        [_moreBtn addTarget:self action:@selector(clickedMoreBtn) forControlEvents:UIControlEventTouchUpInside];
        _moreBtn.titleEdgeInsets = kEdgeInsetsMake(0, 0, 0, 30);
    }
    return _moreBtn;
}

-(UIView *)buleLine2 {
    if (!_buleLine2) {
        long y = 0;
        if ([SAValueManger shareInStance].noServiceMarket == YES) {
            y = -130;
        }
        _buleLine2 = [[UIView alloc] initWithFrame:SARectMake(15, 801 + DifferenceHeight + self.showShop + y, 3, 14)];
        _buleLine2.backgroundColor = kBuleColor;
    }
    return _buleLine2;
}

-(UILabel *)tipLab3 {
    if (!_tipLab3) {
        _tipLab3 = [[UILabel alloc] initWithFrame:SARectMake(15, 549 + DifferenceHeight, 80, 14)];
        _tipLab3.font = kFont(14);
        _tipLab3.textColor = kBlackColor;
        _tipLab3.text = @"服务市场";
        _tipLab3.textAlignment = NSTextAlignmentCenter;
    }
    return _tipLab3;
}

-(UIView *)buleLine3 {
    if (!_buleLine3) {
        _buleLine3 = [[UIView alloc] initWithFrame:SARectMake(15, 549 + DifferenceHeight, 3, 14)];
        _buleLine3.backgroundColor = kBuleColor;
    }
    return _buleLine3;
}

-(UIImageView *)entranceImageV {
    if (!_entranceImageV) {
        _entranceImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScaleNum(577 + DifferenceHeight), kScreenWidth, kScaleNum(80))];
        _entranceImageV.image = [UIImage imageNamed:@"mallEntrance"];
        _entranceImageV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedEntranceImageV)];
        [_entranceImageV addGestureRecognizer:tap];
    }
    return _entranceImageV;
}

-(SAHomeMenuListAPI *)homeMenuListAPI {
    if (!_homeMenuListAPI) {
        _homeMenuListAPI = [SAHomeMenuListAPI apiWithDelegate:self];
    }
    return _homeMenuListAPI;
}

-(NSMutableArray<SAhomeMenuModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASummaryQueryAPI *)summaryQueryAPI {
    if (!_summaryQueryAPI) {
        _summaryQueryAPI = [SASummaryQueryAPI apiWithDelegate:self];
    }
    return _summaryQueryAPI;
}

-(UILabel *)titleLab1 {
    if (!_titleLab1) {
        _titleLab1 = [[UILabel alloc] initWithFrame:SARectMake(0, 60, 115, 14)];
        _titleLab1.text = @"实销数";
        _titleLab1.textColor = kBlackColor;
        _titleLab1.font = kFont(14);
        _titleLab1.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab1;
}

-(UILabel *)titleLab2 {
    if (!_titleLab2) {
        _titleLab2 = [[UILabel alloc] initWithFrame:SARectMake(115, 60, 115, 14)];
        _titleLab2.text = @"实销额";
        _titleLab2.textColor = kBlackColor;
        _titleLab2.font = kFont(14);
        _titleLab2.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab2;
}

-(UILabel *)titleLab3 {
    if (!_titleLab3) {
        _titleLab3 = [[UILabel alloc] initWithFrame:SARectMake(230, 60, 115, 14)];
        _titleLab3.text = @"营业利润";
        _titleLab3.textColor = kBlackColor;
        _titleLab3.font = kFont(14);
        _titleLab3.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab3;
}

-(UILabel *)saleNumLab {
    if (!_saleNumLab) {
        _saleNumLab = [[UILabel alloc] initWithFrame:SARectMake(0, 40, 115, 14)];
        _saleNumLab.text = @"0";
        _saleNumLab.textColor = kBlackColor;
        _saleNumLab.font = kFont(14);
        _saleNumLab.textAlignment = NSTextAlignmentCenter;
    }
    return _saleNumLab;
}

-(UILabel *)salePriceLab {
    if (!_salePriceLab) {
        _salePriceLab = [[UILabel alloc] initWithFrame:SARectMake(115, 40, 115, 14)];
        _salePriceLab.text = @"0";
        _salePriceLab.textColor = kBlackColor;
        _salePriceLab.font = kFont(14);
        _salePriceLab.textAlignment = NSTextAlignmentCenter;
    }
    return _salePriceLab;
}

-(UILabel *)profitsLab {
    if (!_profitsLab) {
        _profitsLab = [[UILabel alloc] initWithFrame:SARectMake(230, 40, 115, 14)];
        _profitsLab.text = @"0";
        _profitsLab.textColor = kBlackColor;
        _profitsLab.font = kFont(14);
        _profitsLab.textAlignment = NSTextAlignmentCenter;
    }
    return _profitsLab;
}

-(UIView *)buleLine {
    if (!_buleLine) {
        _buleLine = [[UIView alloc] initWithFrame:SARectMake(15, 230 + DifferenceHeight, 3, 14)];
        _buleLine.backgroundColor = kBuleColor;
    }
    return _buleLine;
}

-(UIImageView *)tipImageV {
    if (!_tipImageV) {
        _tipImageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScaleNum(697 + DifferenceHeight + self.showShop), kScreenWidth, kScaleNum(90))];
        _tipImageV.backgroundColor = [UIColor whiteColor];
//        _tipImageV.image = [UIImage imageNamed:@"home_tip"];
        _tipImageV.userInteractionEnabled = YES;
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedTipImageV)];
//        [_tipImageV addGestureRecognizer:tap];
    }
    return _tipImageV;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kScaleNum(49 + SafeFooterHeight)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SACommonProblemsCell class] forCellReuseIdentifier:@"SACommonProblemsCell"];
    }
    return _tableView;
}

-(UIView *)tbHeaderview {
    if (!_tbHeaderview) {
        long y = 0;
        if ([SAValueManger shareInStance].noServiceMarket == YES) {
            y = -130;
        }
        _tbHeaderview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(829 + DifferenceHeight + self.showShop + y))];
    }
    return _tbHeaderview;
}

-(UIButton *)eyeBtn {
    if (!_eyeBtn) {
        _eyeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _eyeBtn.frame = SARectMake(207, 125 + DifferenceHeight, 50, 45);
        [_eyeBtn setImage:[UIImage imageNamed:@"home_closeEye"] forState:UIControlStateNormal];
        [_eyeBtn setImage:[UIImage imageNamed:@"home_closeOpen"] forState:UIControlStateSelected];
        [_eyeBtn addTarget:self action:@selector(clickedEyeBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _eyeBtn;
}

-(UIButton *)openPayBtn {
    if (!_openPayBtn) {
        _openPayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _openPayBtn.frame = SARectMake((kBaseScreenWidth - 280)/2, 99 + DifferenceHeight, 280, 28);
        [_openPayBtn setImage:[UIImage imageNamed:@"home_openPay_image"] forState:UIControlStateNormal];
        [_openPayBtn setBackgroundImage:[UIImage imageNamed:@"home_openPay_bg"] forState:UIControlStateNormal];
        [_openPayBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        _openPayBtn.titleLabel.font = kFont(12);
        [_openPayBtn setTitle:@"   您还没有开通扫码支付功能哦！查看详情>>" forState:UIControlStateNormal];
        [_openPayBtn addTarget:self action:@selector(clickedOpenPayBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _openPayBtn;
}

-(UIButton *)storeManagementBtn {
    if (!_storeManagementBtn) {
        _storeManagementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _storeManagementBtn.frame = CGRectMake(kScaleNum(90), kScaleNum(61 + DifferenceHeight), kScaleNum(60), kScaleNum(40));
        [_storeManagementBtn addTarget:self action:@selector(clickedStoreManagementBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _storeManagementBtn;
}

-(UIButton *)myAccountBtn {
    if (!_myAccountBtn) {
        _myAccountBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _myAccountBtn.frame = CGRectMake(kScaleNum(36), kScaleNum(43 + DifferenceHeight), kScaleNum(50), kScaleNum(50));
        [_myAccountBtn addTarget:self action:@selector(clickedMyAccountBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _myAccountBtn;
}

-(UIButton *)profitBtn {
    if (!_profitBtn) {
        _profitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _profitBtn.frame = SARectMake(0, 165 + DifferenceHeight, kBaseScreenWidth, 50);
        [_profitBtn addTarget:self action:@selector(clickedProfitBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _profitBtn;
}

-(SACloudPrintHeartbeatAPI *)cloudPrintHeartbeatAPI {
    if (!_cloudPrintHeartbeatAPI) {
        _cloudPrintHeartbeatAPI = [SACloudPrintHeartbeatAPI apiWithDelegate:self];
    }
    return _cloudPrintHeartbeatAPI;
}

-(SAUserExpireAPI *)userExpireAPI {
    if (!_userExpireAPI) {
        _userExpireAPI = [SAUserExpireAPI apiWithDelegate:self];
    }
    return _userExpireAPI;
}

-(NSMutableArray<SACommonProblemsModel *> *)qwDataMarr {
    if (!_qwDataMarr) {
        _qwDataMarr = [NSMutableArray array];
    }
    return _qwDataMarr;
}

-(SASystemFaqTypeListAPI *)systemFaqTypeListAPI {
    if (!_systemFaqTypeListAPI) {
        _systemFaqTypeListAPI = [SASystemFaqTypeListAPI apiWithDelegate:self];
    }
    return _systemFaqTypeListAPI;
}

-(SAActivityListAPI *)activityListAPI {
    if (!_activityListAPI) {
        _activityListAPI = [SAActivityListAPI apiWithDelegate:self];
    }
    return _activityListAPI;
}

-(SARenewTypeAPI *)renewTypeAPI {
    if (!_renewTypeAPI) {
        _renewTypeAPI = [SARenewTypeAPI apiWithDelegate:self];
    }
    return _renewTypeAPI;
}

-(SAServiceMarketListAPI *)serviceMarketListAPI {
    if (!_serviceMarketListAPI) {
        _serviceMarketListAPI = [SAServiceMarketListAPI apiWithDelegate:self];
    }
    return _serviceMarketListAPI;
}

-(JXCategoryTitleView *)categoryTitleView {
    if (!_categoryTitleView) {
        _categoryTitleView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, kScaleNum(546 + DifferenceHeight), kScreenWidth, kScaleNum(20))];
        _categoryTitleView.titleFont = kFont(14);
        _categoryTitleView.cellSpacing = 30;
        _categoryTitleView.titleSelectedColor = kBuleColor;
        JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
        lineView.indicatorColor = kBuleColor;
        lineView.indicatorWidth = JXCategoryViewAutomaticDimension;
        _categoryTitleView.indicators = @[lineView];
    }
    return _categoryTitleView;
}

-(NSMutableArray<SAServiceMarketMenuModel *> *)serviceMarr {
    if (!_serviceMarr) {
        _serviceMarr = [NSMutableArray array];
    }
    return _serviceMarr;
}

//-------------------------------------------------------------------------------------------------
-(void)bleConnecter {
    if (Manager.bleConnecter == nil) {
        [Manager didUpdateState:^(NSInteger state) {
            switch (state) {
                case CBCentralManagerStateUnsupported:
                    NSLog(@"The platform/hardware doesn't support Bluetooth Low Energy.");
                    break;
                case CBCentralManagerStateUnauthorized:
                    NSLog(@"The app is not authorized to use Bluetooth Low Energy.");
                    break;
                case CBCentralManagerStatePoweredOff:
                    NSLog(@"Bluetooth is currently powered off.");
                    break;
                case CBCentralManagerStatePoweredOn:
                    [self Printer];
                    NSLog(@"Bluetooth power on");
                    break;
                case CBCentralManagerStateUnknown:
                default:
                    break;
            }
        }];
    } else {
        [self Printer];
    }
}

- (void)Printer {
    /* 扫描 */
    NSString *printName2 = kPrint;
    if (printName2.length == 0) {
        return;
    }
    WeakSelf
    self.signal = 0;
    __block int printNum = 0;
    __block int i = 0;
    [Manager scanForPeripheralsWithServices:nil options:nil discover:^(CBPeripheral * _Nullable peripheral, NSDictionary<NSString *,id> * _Nullable advertisementData, NSNumber * _Nullable RSSI) {
        i++;
        if (i > 50) {
            [Manager stopScan];
        }
        
        if ([peripheral.name isEqualToString:kPrint]) {
            self.peripheral = peripheral;
        }
        if (self.peripheral == nil) {
            
        }else {
            weakSelf.isConnection = YES;
            NSString *printOpen = kPrintOpen;
            NSString *printType = kPrintType;
            if ([peripheral.name isEqualToString:@"MHT-P58D"] || [peripheral.name isEqualToString:@"YDT-XP"] || ([printOpen integerValue] == 1 && [peripheral.name isEqualToString:@"MHT-P18L"] && [printType integerValue] == 1)) {
                [Manager stopScan];
                self.overallSetting.printerSetting.printerBleName = peripheral.name;
                [weakSelf ecsAndTsp];
                return;
            }
            [Manager connectPeripheral:self.peripheral options:nil timeout:2 connectBlack:^(ConnectState state) {
                if (state == CONNECT_STATE_CONNECTED) {
                    weakSelf.overallSetting.printerSetting.printType = 2;
                    weakSelf.overallSetting.printerSetting.printerStatus = 2;
                    weakSelf.overallSetting.printerSetting.printerBleName = peripheral.name;
                    if (printNum == 0) {
                        printNum ++;
                        [weakSelf ecsAndTsp];
                    }
                    BLEConnecter *bleConnecter = Manager.bleConnecter;
                    self.signal = 1;
                    [Manager stopScan];
                }else {
                    if (self.signal == 0) {
                        self.overallSetting.printerSetting.printerStatus = 0;
                    }
                    [Manager stopScan];
                }
            }];
        }
    }];
}

//判断类型
-(void)ecsAndTsp {
    
    [SAValueManger shareInStance].printType = 2;
    [self.tableView reloadData];
    
    NSString *printName = kPrint;
    NSString *printOpen = kPrintOpen;
    NSString *printType = kPrintType;
    // 二维码模块大小 1~16
    if ([printName isEqualToString:@"MHT-L58G"] || [printName isEqualToString:@"XP-T202UA"] || ([printOpen integerValue] == 1 && [printName isEqualToString:@"MHT-P18L"] && [printType integerValue] == 2)) {
        [self timerFired];
        self.signal = 0;
    }else if ([printName isEqualToString:@"MHT-P58D"] || [printName isEqualToString:@"YDT-XP"] || ([printOpen integerValue] == 1 && [printName isEqualToString:@"MHT-P18L"] && [printType integerValue] == 1)) {
        NSLog(@"esc");
        [SAValueManger shareInStance].printType = 1;
        [self connectionBluetooth];
    }else {
        unsigned char tscCommand[] = {0x1B, 0x21, 0x3F};
        NSData *tscData = [NSData dataWithBytes:tscCommand length:sizeof(tscCommand)];
        if ([printName isEqualToString:@"MHT-P18L"]) {
            unsigned char tscCommand2[] = {0x10, 0xF0, 0xC1};
            tscData = [NSData dataWithBytes:tscCommand2 length:sizeof(tscCommand2)];
        }
        __block NSString *isReceive = @"0";
        Manager.connecter.readData = ^(NSData * _Nullable data) {
            if ([printName isEqualToString:@"MHT-P18L"]) {
                NSMutableString *hexStr = [NSMutableString string];
                int8_t *bytes = (int8_t *)[data bytes];
                for (int i = 0; i < [data length]; i++) {
                    [hexStr appendFormat:@"%02X",bytes[i]];
                }
                if ([hexStr containsString:@"10F0C10101"]) {
                    isReceive = @"1";
                }
            } else {
                isReceive = @"1";
            }
        };
        [Manager write:tscData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (![isReceive isEqualToString:@"1"]) {
                //esc查询状态指令
                NSLog(@"esc");
                [SAValueManger shareInStance].printType = 1;
                [self connectionBluetooth];
            }else {
                NSLog(@"tsc");
                [self timerFired];
                self.signal = 0;
            }
        });
    }
}

-(void)connectionBluetooth {
    /* 连接外设（先停止扫描，然后断开之前连接，再连接当前外设）*/
    if (self.isConnection == NO) {
        return;
    }
    [Manager close];
    [[BluetoothManager sharedInstance] cancelConnect];//断开小票打印机
    
    __block int i = 0;
    __block int printNum = 0;
    __block CBPeripheral *newPeripheral = nil;
    @try {
        [[BluetoothManager sharedInstance] scanWithSuccess:^(NSArray<CBPeripheral *> * _Nonnull peripheralArray) {
            NSLog(@"scanWithSuccess：%lu",(unsigned long)peripheralArray.count);
            i++;
            if (i == 100) {
                self.overallSetting.printerSetting.printerStatus = 0;
                [[BluetoothManager sharedInstance] stopScan];
                return;
            }
            
            for (CBPeripheral *peripheral2 in peripheralArray) {
                if ([peripheral2.name isEqualToString:self.overallSetting.printerSetting.printerBleName]) {
                    newPeripheral = peripheral2;
                }
            }
            
            if (newPeripheral != nil && printNum == 0) {
                printNum++;
                [[BluetoothManager sharedInstance] stopScan];
                [[BluetoothManager sharedInstance] connect:newPeripheral didConnectPeripheral:^(CBPeripheral * _Nonnull peripheral) {
                    // 打印机已连接
                    self.overallSetting.printerSetting.printerStatus = 2;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                    self.overallSetting.printerSetting.printerBleName = peripheral.name;
                    self.overallSetting.printerSetting.printType = 1;
                    self.overallSetting.printerSetting.peripheral = peripheral;
                    self.signal = 0;
                    [self timerFired];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                    [SAValueManger shareInStance].oldPrint = NO;
                    //根据目前适配的打印机，命名规则都不同，现在根据命名区分打印机型号，黑色打印机的在大家二维码的时候会有问题，如果后期有改动这里
                    //要想办法处理二维码大小问题！
                    NSArray<NSString *> *nameMarr = [peripheral.name componentsSeparatedByString:@"_"];
                    if (nameMarr.count == 2) {
                        if ([@"Printer" isEqualToString:nameMarr[0]]) {
                            [SAValueManger shareInStance].oldPrint = YES;
                        }
                    }
                } didFailToConnectPeripheral:^(CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
                    // 打印机连接失败
                    self.overallSetting.printerSetting.printerStatus = 0;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                    self.overallSetting.printerSetting.printerBleName = @"";
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                    self.signal = 0;
                } didDisconnectPeripheral:^(CBPeripheral * _Nonnull peripheral, NSError * _Nonnull error) {
                    // 打印机失去连接
                    self.overallSetting.printerSetting.printerStatus = 0;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
                    self.overallSetting.printerSetting.printerBleName = @"";
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
                    self.signal = 0;
                }];
            }
            //        else {
            //            [Prompt popPromptViewWithMsg:@"请重新设置打印模式" duration:5];
            //            [kUserDefault setObject:@"0" forKey:kPrintOpenKey];
            //            self.signal = 0;
            //            self.overallSetting.printerSetting.printerStatus = 0;// 0-打印机未连接    1-打印机正在连接    2-打印机已连接
            //            self.overallSetting.printerSetting.printerBleName = @"";
            //            [[BluetoothManager sharedInstance] stopScan];
            //            [[BluetoothManager sharedInstance] cancelConnect];//断开小票打印机
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"kOverallSettingDidChanged" object:nil];
            //        }
            
        } failure:^(CBCentralManagerState state, NSString * _Nonnull stateMessage) {
            NSLog(@"scanWithFailure：%ld，%@",(long)state, stateMessage);
            [Prompt popPromptViewWithMsg:stateMessage duration:2];
        }];
    } @catch (NSException *exception) {
        [Prompt popPromptViewWithMsg:@"请重新设置打印模式" duration:5];
        [kUserDefault setObject:@"0" forKey:kPrintOpenKey];
    } @finally {
        
    }
}

@end

